package com.sx.netty.netty.demo04_idle;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.HashedWheelTimer;

import java.util.concurrent.TimeUnit;

/**
 * @Author ShuXin
 * @Description
 * @Date 2020/12/10 15:26
 */
public class HeartBeatsClient {
    protected final HashedWheelTimer timer = new HashedWheelTimer();
    private Bootstrap bootstrap;
    private final ConnectorIdleStateTrigger idleStateTrigger = new ConnectorIdleStateTrigger();

    public void connect(String host, int port) throws Exception {
        NioEventLoopGroup group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO));
        final ConnectionWatchdog connectionWatchdog = new ConnectionWatchdog(bootstrap, timer, port, host, true) {
            public ChannelHandler[] handlers() {
                return new ChannelHandler[]{
                        this,
                        new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS),
                        idleStateTrigger,
                        new StringEncoder(),
                        new StringDecoder(),
                        new HeartBeatClientHandler()
                };
            }
        };
        ChannelFuture future;
        try {
            synchronized (bootstrap) {
                bootstrap.handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(connectionWatchdog.handlers());
                    }
                });
                future = bootstrap.connect(host, port);
            }
            future.sync();
        } catch (Exception e) {
            throw new Exception("连接失败", e);
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.parseInt(args[0]);
            } catch (NumberFormatException e){
                //采用默认值
            }
        }

        new HeartBeatsClient().connect("127.0.0.1", port);
    }
}
